package com.czw.ali.register

import android.app.Application
import android.content.Context
import android.content.DialogInterface
import com.blankj.utilcode.util.LogUtils
import com.didi.drouter.annotation.Service
import com.mtzqc.common.BuildConfig
import com.mtzqc.common.init.AgreeService
import com.mtzqc.common.task.ITask
import com.taobao.monitor.procedure.Header.ttid
import com.taobao.update.IUpdateLog
import com.taobao.update.adapter.UpdateAdapter
import com.taobao.update.apk.ApkDownloadListener
import com.taobao.update.apk.ApkUpdater
import com.taobao.update.common.Config
import com.taobao.update.common.framework.UpdateRuntime
import com.taobao.update.datasource.UpdateDataSource


@Service(
    function = [AgreeService::class],
    priority = 20
)
class UpdateRegister(
) : AgreeService {
    override val dependsLib: Array<Class<out ITask>>?
        get() = null
    override val depends: Array<String>?
        get() = null
    override val depName: String
        get() = "Update"
    override val priority: Int
        get() = 20

    override fun executeInit(app: Application, debug: Boolean, dev: Boolean): Boolean {
        //以下引号部分需要客户根据自己的应用进行配置（）
        val config = Config()
        //填写appkey
        config.group = "${BuildConfig.EMAS_APP_KEY}@android"
        //渠道号
        config.ttid = ttid
        config.isOutApk = false
        //app name
        config.appName = BuildConfig.appName
        //设置自定义弹窗
         setCustomDialog(app, false)
        //初始化
        UpdateRuntime.init(app, config.ttid, config.appName, config.group)
        UpdateDataSource.getInstance().apply {
            init(
                app, config.group,  config.ttid, config.isOutApk,
               "27949820", "bdf870f6f637cb92241b27ebcb5feec5", ttid, UpdateAdapter()
            )
            //设置是否开启缓存，true开启，false关闭
            isEnableCache = false
            //设置缓存有效时间,单位ms，eg: 缓存有效时间3h
            cacheValidTime = (3 * 60 * 60 * 1000).toLong()
            //true:同步, false:异步
            startUpdate(false)
        }
        return true
    }

    /* 设置自定义弹窗
     * @param context Context
     * @param customDialog 是否自定义弹窗
     */
    private fun setCustomDialog(context: Context, customDialog: Boolean) {
        val apkUpdate = ApkUpdater(context)
        apkUpdate.setUpdateLog(object : IUpdateLog {
            override fun d(s: String) {
                LogUtils.e(s)
            }
            override fun d(s: String, throwable: Throwable) {
                LogUtils.e(s,throwable)
            }
            override fun e(s: String) {
                LogUtils.e(s)
            }
            override fun e(s: String, throwable: Throwable) {
                LogUtils.e(s,throwable)
            }
            override fun i(s: String) {
                LogUtils.e(s)
            }
            override fun i(s: String, throwable: Throwable) {
                LogUtils.e(s,throwable)
            }
            override fun w(s: String) {
                LogUtils.e(s)
            }
            override fun w(s: String, throwable: Throwable) {
                LogUtils.e(s,throwable)
            }
            override fun v(s: String)
            {
                LogUtils.e(s)
            }
            override fun v(s: String, throwable: Throwable) {
                LogUtils.e(s,throwable)
            }
        })
        //设置apk下载进度回调
        apkUpdate.setApkDownloadListener(object : ApkDownloadListener {
            override fun onPreDownload() {
                //下载开始
                LogUtils.e("onPreDownload")
            }

            override fun onDownloadProgress(progress: Int) {
                //下载进行中
                LogUtils.e("progress"+progress)
            }

            override fun onStartFileMd5Valid(filePath: String, fileSize: String) {
                //开启文件md5校验
                LogUtils.e("onStartFileMd5Valid"+filePath+fileSize)

            }

            override fun onFinishFileMd5Valid(success: Boolean) {
                //完成文件校验
                LogUtils.e("onFinishFileMd5Valid"+success)
            }

            override fun onDownloadFinish(url: String, filePath: String) {
                //下载完成
                LogUtils.e("onDownloadFinish"+url+filePath)

            }

            override fun onDownloadError(url: String, errorCode: Int, msg: String) {
                //下载出错
                LogUtils.e("onDownloadError"+url+errorCode)

            }
        })
        if (customDialog) {
            //自定义有更新信息时的Dialog
           /* apkUpdate.setUpdateNotifyListener { activity, customUpdateInfo, userAction ->
                val builder: AlertDialog.Builder = Builder(activity)
                builder.setTitle("新版本升级")
                builder.setMessage(
                    """
                ${customUpdateInfo.info}
                版本：${customUpdateInfo.version}
                安装包大小：${customUpdateInfo.size}
                是否强制升级：${customUpdateInfo.isForceUpdate}
                """.trimIndent()
                )
                builder.setCancelable(false)
                builder.setPositiveButton(userAction.confirmText,
                    DialogInterface.OnClickListener { dialogInterface, i ->
                        userAction.onConfirm()
                        dialogInterface.dismiss()
                    })
                builder.setNegativeButton(userAction.cancelText,
                    DialogInterface.OnClickListener { dialogInterface, i ->
                        userAction.onCancel()
                        dialogInterface.dismiss()
                    })
                builder.create().show()
            }
            //如果是强制更新，用户点击更新Dialog的取消按钮时会弹出这个Dialog；如果不是强制更新，则不会弹出这个Dialog
            apkUpdate.setCancelUpdateNotifyListener { activity, customUpdateInfo, userAction ->
                val builder: AlertDialog.Builder = Builder(activity)
                builder.setTitle("强制升级取消提示")
                builder.setMessage(customUpdateInfo.info)
                builder.setCancelable(false)
                builder.setPositiveButton(userAction.confirmText,
                    DialogInterface.OnClickListener { dialogInterface, i ->
                        userAction.onConfirm()
                        dialogInterface.dismiss()
                    })
                builder.setNegativeButton(userAction.cancelText,
                    DialogInterface.OnClickListener { dialogInterface, i ->
                        userAction.onCancel()
                        dialogInterface.dismiss()
                    })
                builder.create().show()
            }
            //apk下载完成后，安装Dialog
            apkUpdate.setInstallUpdateNotifyListener { activity, customUpdateInfo, userAction ->
                val builder: AlertDialog.Builder = Builder(activity)
                builder.setTitle("个性化安装")
                builder.setMessage(customUpdateInfo.info)
                builder.setCancelable(false)
                builder.setPositiveButton(userAction.confirmText,
                    DialogInterface.OnClickListener { dialogInterface, i ->
                        userAction.onConfirm()
                        dialogInterface.dismiss()
                    })
                builder.setNegativeButton(userAction.cancelText,
                    DialogInterface.OnClickListener { dialogInterface, i ->
                        userAction.onCancel()
                        dialogInterface.dismiss()
                    })
                builder.create().show()
            }
            //自定义更新结果提示
            apkUpdate.setUpdateResultListener { i, i1, s -> }*/
        } else {
            //接口设为null，则弹窗默认使用SDK内置的Dialog
            apkUpdate.setUpdateNotifyListener(null)
            apkUpdate.setCancelUpdateNotifyListener(null)
            apkUpdate.setInstallUpdateNotifyListener(null)
        }
    }
}